const Router = require('koa-router')
const uuid = require('uuid')
const { check, catchError, generateOk } = require('../../lib/check')
const { getAllNotices, searchNotice, editNotice, deleteNotice, setNotice } = require('../../model/notice')
let notice = new Router()

notice.post("/get", async (ctx) => {
  try {
    const data = ctx.request.body
    const notices = getAllNotices()
    let newNotices = notices
    if (data.create_Ts === 'descend') {
      newNotices = newNotices.sort((a, b) => Number(b.create_Ts) - Number(a.create_Ts))
    } else {
      newNotices = newNotices.sort((a, b) => Number(a.create_Ts) - Number(b.create_Ts))
    }
    if (data.statu !== undefined) {
      newNotices = newNotices.filter((item) => item.statu === data.statu)
    }
    if (!!data.content) {
      newNotices = newNotices.filter(item => item.content.includes(data.content))
    }
    const start = data.offset === undefined ? 0 : data.offset
    const size = data.limit === undefined ? 7 : data.limit
    const resData = newNotices.slice(start, start + size)
    ctx.body = generateOk({ data: resData, total: newNotices.length, length: resData.length })
  } catch (e) {
    catchError(e, ctx)
  }
})

notice.post('/changeStatu', async (ctx) => {
  try {
    const data = ctx.request.body
    check(!!data.content, 'Params_Lost')
    // check(!!data.id, 'Params_Lost')
    // check(data.state !== undefined, 'Params_Lost')
    const findNotice = searchNotice(data.content)
    check(findNotice, 'Not_Notice')
    editNotice({ ...findNotice, statu: findNotice.statu === 0 ? 1 : 0 })
    ctx.body = generateOk({ ...findNotice, statu: findNotice.statu === 0 ? 1 : 0 })
  } catch (e) {
    catchError(e, ctx)
  }
})

notice.post('/remove', async (ctx) => {
  try {
    const data = ctx.request.body
    check(data.content, 'Params_Lost')
    const findNotice = searchNotice(data.content)
    check(findNotice, 'Not_Notice')
    deleteNotice(data.content)
    ctx.body = generateOk({ ...findNotice })
  } catch (e) {
    catchError(e, ctx)
  }
})

notice.post('/add', async (ctx) => {
  try {
    const data = ctx.request.body
    check(!!data.content, 'Params_Lost')
    check(data.statu !== undefined, 'Params_Lost')
    const findNotice = searchNotice(data.content)
    check(!findNotice, 'Notice_Has_Been_Exist')
    const param = {
      ...data,
      create_Ts: new Date().getTime().toString()
    }
    setNotice(param)
    ctx.body = generateOk(param)
  } catch (e) {
    catchError(e, ctx)
  }
})

module.exports = notice